function addEvent(data,div_to_add){
    var $eventDiv = document.createElement("div"); 
    $eventDiv.id= "event"+data.id;
    //$eventDiv.className = "well";
    $(div_to_add).append($eventDiv);
    
    if(data.descripcion.length > 300){
        data.descripcion = data.descripcion.substring(0,299) + "..." ;
    }
    
                $eventDiv.innerHTML =      
        '<div class="row"><a href="event.jsp?id='+data.id +'">'+ data.titulo +'</a><div class="span8"><div class="row"><div class="span8">\n\
    <h4><strong></strong></h4></div></div>\n\
    <div class="row"><div class="span2"><a href="#" class="thumbnail">\n\
    <img src="https://upload.wikimedia.org/wikipedia/commons/d/df/Gnome_globe_current_event.svg" height="180" width="260" alt="'+data.titulo+'"></a></div>\n\
    <div class="span6"><p>'+data.descripcion+'</p>\n\
    <p><a class="btn" href="event.jsp?id='+data.id+'>Ir a la oferta</a>\n\
    Ir a la oferta</a></p></div></div><div class="row"><div class="span8"><p></p>\n\
    <p><i class="icon-user"></i> por <a href="#">anonymous'+  +'</a>  | <i class="icon-calendar">\n\
    </i> TODO Sept 16th, 2012        | <i class="icon-comment"></i> \n\
    <a href="#">0 Comentarios</a>| <i class="icon-share"></i> <a href="#">Compartir</a> |\n\
     <i class="icon-tags"></i> Tags :</p></div></div></div>	</div><hr>'
        ;
                      
//    var $titleAndDescription = document.createElement("div");
//    $titleAndDescription.id = "titleAndDescription" ;
//    $titleAndDescription.className = "event_content";
//    if(data.descripcion.length > 300){
//        data.descripcion = data.descripcion.substring(0,299) + "..." ;
//    }
//    $titleAndDescription.innerHTML = "<b><a href='event.jsp?id="+data.id +"'>"+ data.titulo +"</a></b> - "+ data.descripcion +"" ;
//    $eventDiv.appendChild($titleAndDescription);
//                        
//    var $fecha_pub = document.createElement("div"); 
//    $fecha_pub.className = "fecha_pub pull-right";
//    $fecha_pub.innerHTML = "Posted at: "+data.fechaPublicacion; 
//    $eventDiv.appendChild($fecha_pub);
////                        var $fecha_inicio = "<div class='event_fecha_inicio'>"+data.fechaInicio +"</div>";
////                        var $fecha_fin = "<div class='event_fecha_fin'>"+data.fechaFin +"</div>";
////                        var $fecha_pub = "<div class='event_fecha_pub'>"+data.fechaPublicacion +"</div>";
////                        
//                              
//     
}
            
function eventExists(event_id,div_id){
    var result = false;
    //    console.log(div_children);
    if($(div_id).find("#event"+event_id).length > 0){
        result = true;
    }
    return result;
}

function loadMainEvents(){
    loadTodayEvents();
    loadLatestEvents();
    loadMostPopularEvents();  
}       
                                
function loadTodayEvents(){
    console.log("today");
    $.ajax({
        //                        doesn't work if u put->  url: "Bxip/rest/events/getTodays" 
        url: "/Bxip/rest/events/getTodays",
        dataType: 'json',
        success:  function(data) {
            if (data != null && data.length != 0) {
                for ( var i = 0; i < data.length; i++) {
                    if(!eventExists(data[i].id,"#today_events")){
                        addEvent(data[i],"#today_events");
                    }
                }
            }
        }
    });
}

function loadMostPopularEvents(){
    console.log("most");
    $.ajax({
        //                        doesn't work if u put->  url: "Bxip/rest/events/" 
        url: "/Bxip/rest/events/getMostPopular",
        dataType: 'json',
        success:  function(data) {
            if (data != null && data.length != 0) {
                for ( var i = 0; i < data.length; i++) {
                    if(!eventExists(data[i].id,"#most_popular")){
                        addEvent(data[i],"#most_popular");
                    }
                }
            }
        }
    });
}
function loadLatestEvents(){
    console.log("load");
    $.ajax({
        //                        doesn't work if u put->  url: "Bxip/rest/events/" 
        url: "/Bxip/rest/events/getLatests",
        dataType: 'json',
        success:  function(data) {
            if (data != null && data.length != 0) {
                for ( var i = 0; i < data.length; i++) {
                    if(!eventExists(data[i].id),"#latest_events"){
                        addEvent(data[i],"#latest_events");
                    }
                }
            }
        }
    });
}


function loadEventByID(id){
    console.log("colled");
    $.ajax({
        //                        doesn't work if u put->  url: "Bxip/rest/events/" 
        url: "/Bxip/rest/events/"+id,
        dataType: 'json',
        success:  function(data) {
            if (data != null && data.length != 0) {  
                document.getElementById("event_title").innerHTML = "<h3>"+data.titulo+"</h3>";
                document.getElementById("event_start_date").innerHTML = data.fechaInicio ;
                document.getElementById("event_last_date").innerHTML = data.fechaFin ;
                document.getElementById("event_pub_date").innerHTML = data.fechaPublicacion ;
                document.getElementById("event_description").innerHTML = data.descripcion ;
            }
        }
    });
}


function send_create_event(){
    //    TODO: Add commented functionality
    var title = $("#input_title").val();
    var fechaInicio = $("#input_when").val();
    var donde = $("#inputWhere").val();
    var categoria = $("#input_category option:selected").val();
    //var image = $("#input_event_image");
    var description = $("#input_description").val();
    //    var fechaFin = $("#input_fechaFin").val();
    var fechaFin = "forever";
    
    console.log("Sending event creation --- : " + fechaInicio + donde  +  categoria + description + title);
    
    
    //    JSON.stringify({
    //        titulo:title, 
    //        Project:{
    //            Id:1
    //        }
    //    });
    
    $.ajax({
        url: "/Bxip/rest/events/",
        dataType: 'json',
        method: "PUT",
        type: "post",
        data: '{"titulo":' + title + ',"descripcion:"'+description+',"fechaInicio:"'+fechaInicio+ ',"lugar:"'+donde+',"fechaFin:"'+fechaFin+' }',
        contentType: "application/json; charset=utf-8",
        success: function(data) {
            console.log("success ", data.response);
        },
        error: function(data) {
            console.log("error ", data.error);
        }
    });
    
 
    
}
   
   
//Utils
   
   
function countChildElements(parent, child)
{
    var parent = document.getElementById(parent);
    var childCount = parent.getElementsByTagName(child).length;
    alert(childCount);
}



/* Copyright (c) 2006 Mathias Bank (http://www.mathias-bank.de)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting and fixing.
 */
jQuery.extend({
    /**
* Returns get parameters.
*
* If the desired param does not exist, null will be returned
*
* @example value = $.getURLParam("paramName");
*/ 
    getURLParam: function(strParamName){
        var strReturn = "";
        var strHref = window.location.href;
        var bFound=false;
	  
        var cmpstring = strParamName + "=";
        var cmplen = cmpstring.length;

        if ( strHref.indexOf("?") > -1 ){
            var strQueryString = strHref.substr(strHref.indexOf("?")+1);
            var aQueryString = strQueryString.split("&");
            for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
                if (aQueryString[iParam].substr(0,cmplen)==cmpstring){
                    var aParam = aQueryString[iParam].split("=");
                    strReturn = aParam[1];
                    bFound=true;
                    break;
                }
	      
            }
        }
        if (bFound==false) return null;
        return strReturn;
    }
});